<template>
  <div>
    <AForm :model="searchFrom" class="erp-search-form">
      <ARow class="grid-demo" :gutter="10">
        <ACol :span="6">
          <AFormItem hide-label content-class="">
            <AInput v-model="searchFrom.materialName" placeholder="产品名称" />
          </AFormItem>
        </ACol>
        <ACol :span="6">
          <AFormItem hide-label content-class="">
            <AInput v-model="searchFrom.spec" placeholder="规格" />
          </AFormItem>
        </ACol>
        <ACol :span="6">
          <AFormItem hide-label content-class="">
            <ARangePicker
              v-model="searchFrom.createTime"
              format="YYYY-MM-DD"
              :placeholder="['创建时间-创建', '创建时间-结束']"
            ></ARangePicker>
          </AFormItem>
        </ACol>
        <ACol :span="6">
          <AFormItem hide-label content-class="">
            <ASelect v-model="searchFrom.isWarned" placeholder="是否警告" allow-clear>
              <AOption label="否" :value="0"></AOption>
              <AOption label="是" :value="1"></AOption>
            </ASelect>
          </AFormItem>
        </ACol>
      </ARow>
    </AForm>
    <ACard>
      <div class="erp-mb-10 w100 erp-search-btn-box">
        <ASpace>
          <AButton type="primary" @click="onSearch">
            <template #icon>
              <icon-search />
            </template>
          </AButton>
          <ATooltip content="清空筛选项" position="top">
            <AButton type="dashed" @click="onReset">
              <template #icon>
                <icon-refresh />
              </template>
            </AButton>
          </ATooltip>
          <AButton v-if="isAuth([1, 2])" type="outline" @click="openEdit('新增')">新增</AButton>
          <ATooltip
            v-if="isAuth([1, 2])"
            :disabled="!isEmpty(selectedRowKeys)"
            content="请选择数据"
          >
            <AButton status="danger" @click="batchDel()">批量删除</AButton>
          </ATooltip>
          <tableImp
            v-if="isAuth([1, 2])"
            imp-url="/produce/materialStockImport"
            :file-temp="() => onExport('template')"
            :other-param="{ materialType: 1 }"
            @end-call-back="onSearch"
          ></tableImp>
        </ASpace>
        <ASpace>
          <AButton type="primary" :loading="exportLoad" @click="onExport('table')">导出</AButton>
          <ADropdownButton>
            {{ ['名称排序', '时间排序'][orderBy] }}
            <template #icon>
              <icon-down />
            </template>
            <template #content>
              <ADoption
                :value="0"
                @click="
                  () => {
                    orderBy = 0
                    onSearch()
                  }
                "
              >
                名称排序
              </ADoption>
              <ADoption
                :value="1"
                @click="
                  () => {
                    orderBy = 1
                    onSearch()
                  }
                "
              >
                时间排序
              </ADoption>
            </template>
          </ADropdownButton>
        </ASpace>
      </div>
      <ATable
        ref="tableRef"
        v-model:selected-keys="selectedRowKeys"
        :pagination="false"
        :data="tableData"
        :bordered="{ cell: true }"
        :span-method="spanMethod"
        column-resizable
        size="small"
        row-key="materialStockId"
        :row-class="setRowClass"
      >
        <template #columns>
          <ATableColumn title="序号" data-index="rowIndex" :width="65" align="center">
            <template #cell="{ rowIndex }">
              <div>{{ rowIndex + 1 }}</div>
            </template>
          </ATableColumn>
          <ATableColumn title="产品名称" data-index="materialName" :width="100"></ATableColumn>
          <ATableColumn title="类别" data-index="materialCategory" :width="100"></ATableColumn>
          <ATableColumn title="规格型号" data-index="spec" :width="100"></ATableColumn>
          <ATableColumn title="存放区" data-index="storageArea" :width="100"></ATableColumn>
          <ATableColumn title="库存数量" data-index="stockQty" :width="100"></ATableColumn>
          <ATableColumn title="单价" data-index="unitPrice" :width="100"></ATableColumn>
          <ATableColumn title="金额" data-index="amount" :width="100">
            <template #cell="{ record }">
              <div>{{ `¥${formatPrice(record.unitPrice * record.stockQty)}` }}</div>
            </template>
          </ATableColumn>
          <ATableColumn title="创建时间" data-index="createdDt" :width="155" align="center">
            <template #cell="{ record }">
              <div>{{ dayjs(record.createdDt).format('YYYY-MM-DD') }}</div>
            </template>
          </ATableColumn>
          <ATableColumn title="更新时间" data-index="remark" :width="155" align="center">
            <template #cell="{ record }">
              <div>{{ dayjs(record.updatedDt).format('YYYY-MM-DD') }}</div>
            </template>
          </ATableColumn>
          <ATableColumn v-if="isAuth([1, 2])" title="操作" :width="150" fixed="right">
            <template #cell="{ record }">
              <ASpace>
                <AButton type="primary" size="mini" @click="rowEvent(record, 'edit')">
                  修改
                </AButton>
                <AButton status="danger" size="mini" @click="rowEvent(record, 'del')">
                  删除
                </AButton>
              </ASpace>
            </template>
          </ATableColumn>
        </template>
      </ATable>
      <div class="arco-table-pagination">
        <APagination
          :total="pageParam.totalCount"
          :page-size="pageParam.pageSize"
          show-total
          @change="(page: number) => tableEvent('page-change', page)"
        />
      </div>
    </ACard>
    <EditPopupForm
      v-model:visible="editModal"
      :title="editModalTitle"
      :check-data="rowData"
      @reload="
        () => {
          getTableData()
          clearTableSelect()
        }
      "
    ></EditPopupForm>
  </div>
</template>

<script lang="ts" setup>
import EditPopupForm from './editPopupForm.vue'
import quotationPrint from './print.vue'
import dayjs from 'dayjs'
import { formatPrice } from '@renderer/utils/mixins'
import { Message, Modal, TableInstance } from '@arco-design/web-vue'
import { isAuth } from '@renderer/utils/auth'
import {
  batchDelStock,
  delStock,
  getStockAllList,
  getStockPageList,
  StockResItem,
  StockSearch
} from '@renderer/api/warehouseManage'
import tableImp from '@renderer/components/table/import.vue'
import { getTemplateUrl } from '@renderer/api/common'
import { downloadFile } from '@renderer/utils/mixins'
import { isEmpty } from 'lodash-es'

const searchFrom = ref<StockSearch>({})
const editModal = ref(false)
const editModalTitle = ref('新增')
const tableData = ref<StockResItem[]>([])
const pageParam = reactive({
  currentPage: 1,
  pageSize: 20,
  totalCount: 0
})
const quotationPrintRef = ref<InstanceType<typeof quotationPrint>>() // 打印组件
const orderBy = ref(0)
const selectedRowKeys = ref<string[]>([])
const tableRef = ref<TableInstance>()

onMounted(() => {
  getTableData()
})

function clearTableSelect() {
  tableRef.value?.selectAll(false)
  selectedRowKeys.value = []
}

async function getTableData() {
  const [createdStartDate, createdEndDate] = searchFrom.value.createTime! || []
  searchFrom.value.createdStartDate = createdStartDate
    ? dayjs(createdStartDate).format('YYYY-MM-DD')
    : ''
  searchFrom.value.createdEndDate = createdEndDate ? dayjs(createdEndDate).format('YYYY-MM-DD') : ''
  const res = await getStockPageList({
    ...searchFrom.value,
    ...pageParam,
    materialType: 1,
    orderBy: orderBy.value
  })
  tableData.value = res.data.list
  pageParam.totalCount = res.data.totalCount!
}

const onSearch = () => {
  pageParam.currentPage = 1
  getTableData()
}

function onReset() {
  searchFrom.value = {}
  pageParam.currentPage = 1
  pageParam.pageSize = 20
  getTableData()
}

function batchDel() {
  batchDelStock({ idList: selectedRowKeys.value }).then(() => {
    Message.success('删除成功')
    onSearch()
    clearTableSelect()
  })
}

function setRowClass(record: StockResItem) {
  if (record.stockWarningQty == null) return
  return record.stockWarningQty >= (record.stockQty || 0) ? 'warning' : ''
}

function tableEvent(type: 'page-change', param: any) {
  switch (type) {
    case 'page-change':
      pageParam.currentPage = param
      getTableData()
      break

    default:
      break
  }
}

const spanMethod = ({ record, columnIndex }) => {
  if (columnIndex < 2) {
    if (record.span) {
      return {
        colspan: 1,
        rowspan: record.span
      }
    }
  }
}

function openEdit(title: string) {
  rowData.value = {}
  editModalTitle.value = title
  editModal.value = true
}

const rowData = ref({})

function rowEvent(row: StockResItem, type: 'del' | 'copy' | 'edit' | 'print') {
  switch (type) {
    case 'del':
      Modal.warning({
        title: '警告',
        content: '当前数据删除后不可恢复，是否继续？',
        okText: '确认',
        cancelText: '取消',
        simple: false,
        hideCancel: false,
        maskClosable: false,
        closable: false,
        onOk: () => {
          delStock({ materialStockId: row.materialStockId! }).then(() => {
            Message.success('删除成功')
            getTableData()
          })
        },
        onCancel: () => {}
      })
      break
    case 'copy':
      rowData.value = row
      editModalTitle.value = '新增'
      editModal.value = true
      break
    case 'edit':
      rowData.value = row
      editModalTitle.value = '修改'
      editModal.value = true
      break
    case 'print':
      rowData.value = row
      nextTick(() => {
        quotationPrintRef.value?.printInfo()
      })
      break

    default:
      break
  }
}

const exportLoad = ref(false)

async function onExport(type: 'table' | 'template') {
  let fileTitle: string
  exportLoad.value = true
  const headerData = [
    { title: '产品名称', value: 'materialName', width: 180 },
    { title: '类别', value: 'materialCategory' },
    { title: '规格型号', value: 'spec' },
    { title: '存放区', value: 'storageArea' },
    { title: '库存数量', value: 'stockQty' },
    { title: '单价', value: 'unitPrice' },
    { title: '金额', value: 'amount' }
  ]
  let excelData: StockResItem[] = []
  switch (type) {
    case 'table':
      {
        fileTitle = '辅料库存'
        headerData.unshift({ title: '序号', value: 'index', width: 80 })
        const res = await getStockAllList({ ...searchFrom.value, materialType: 1 })
        excelData = res.data.list.map((item, index) => {
          item.index = index + 1
          item.amount = `¥${formatPrice((item.unitPrice || 0) * (item.stockQty || 0))}`
          return item
        })
        import('@renderer/utils/vendor').then((excel) => {
          excel.exportExcel(excelData, headerData, fileTitle)
          exportLoad.value = false
        })
      }
      break
    case 'template':
      getTemplateUrl('/produce/materialStockTemplateUrl').then((res) => {
        downloadFile(res.data)
      })
      break

    default:
      break
  }
}
</script>
<style lang="less" scoped>
.erp-search-btn-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.warning .arco-table-td) {
  color: red;
}
</style>
